package com.dalin.demo.controller;

import com.dalin.demo.pojo.entity.*;
import com.dalin.demo.service.StudentCourseService;
import com.dalin.demo.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/teachers")
@CrossOrigin(origins = "*")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;


    @GetMapping("/list")
    public List<Teacher> listTeachers(@RequestParam Map<String, Object> params) {
        System.out.println("listTeacher by params==="+ params);
        return teacherService.listTeachersByParams(params);
    }

    @PostMapping("/add")
    public Teacher addTeacher(@RequestBody Teacher teacher) throws Exception {
        System.out.println("addTeacher==="+teacher);
        teacherService.addTeacher(teacher);
        return teacher;
    }

    @PostMapping("/edit")
    public String updateTeacher(@RequestBody Teacher teacher) throws Exception {
        teacherService.updateTeacher(teacher);
        return "success";
    }

    @DeleteMapping("/delete/{id}")
    public String deleteTeacher(@PathVariable Integer id) {
        System.out.println("deleteTeacher by id==="+ id);
        teacherService.deleteTeacher(id);
        return "success";
    }

    @PostMapping("/enrollClass")
    public ResponseEntity<?> enrollTeacherToCourse(@RequestBody EnrollTeacherRequest request) {
        try {
            List<TeacherCourse> teacher = request.getCourseIds().stream()
                    .map(courseId -> new TeacherCourse(courseId,request.getTeacherId()))
                    .collect(Collectors.toList());

            teacherService.batchAddClass(teacher);
            return ResponseEntity.ok("Students successfully enrolled to the course");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error enrolling students to the course");
        }
    }

    @GetMapping("/enrolledCourse/{teacherId}")
    public ResponseEntity<?> getEnrolledTeacher(@PathVariable Long teacherId) {
        try {
            List<TeacherCourse> teacherCourses = teacherService.getEnrolledTeacherByCourseId(teacherId);
            System.out.println(teacherCourses);
            return ResponseEntity.ok(teacherCourses);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error retrieving enrolled students");
        }
    }

    @DeleteMapping("/deleteTea/{id}")
    public String deleteTeachers(@PathVariable Integer id) {
        System.out.println("deleteTeacher by id==="+ id);
        teacherService.deleteTeachers(id);
        return "success";
    }
}